package logic

import (
	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"
	"book/models/cache"
	"book/models/mysql"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *bookrpc.LoginRequest) (*bookrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.RDB.Get(l.ctx, "captcha"+in.Account).Result()

	if in.CaptchaCode != result {
		return nil, fmt.Errorf("图形验证码错误请重新输入")
	}

	result1, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()

	if in.SmsCode != result1 {
		return nil, fmt.Errorf("短信验证码错误请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在")
	}

	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}

	login := mysql.UserLogin{
		UserId: int64(user.ID),
	}

	mysql.DB.Debug().Create(&login)

	return &bookrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
